package xuanzhen.reservation.controller;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTCreatorTest;
import com.auth0.jwt.RandomP;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;

import net.sf.json.JSONArray;
import xuanzhen.christian.pojo.ChrisCus;
import xuanzhen.christian.service.ChrisService;
import xuanzhen.dating.pojo.DatingUser;
import xuanzhen.dating.pojo.SeeShare;
import xuanzhen.dating.pojo.SignList;
import xuanzhen.dating.service.DatingService;
import xuanzhen.dating.service.SeeShareService;
import xuanzhen.manage.pojo.Admins;
import xuanzhen.manage.service.AdminsService;
import xuanzhen.pro.pojo.Relay;
import xuanzhen.pro.service.RelayService;
import xuanzhen.reservation.pojo.BlackUser;
import xuanzhen.reservation.pojo.RedPacket;
import xuanzhen.reservation.pojo.Reservation;
import xuanzhen.reservation.service.BlackUserService;
import xuanzhen.reservation.service.PostManService;
import xuanzhen.reservation.service.RedPacketService;
import xuanzhen.reservation.service.ReservationService;
import xuanzhen.wx.pojo.AccessToken;
import xuanzhen.wx.pojo.Jsticket;
import xuanzhen.wx.pojo.WxUserMsg;
import xuanzhen.wx.service.CoreService;
import xuanzhen.wx.util.EmojiFilter;
import xuanzhen.wx.util.WeixinUtil;
import xuanzhen.wx.util.fina.WxSet;

@Controller
@RequestMapping("/resercus")
public class ResercusController {
	@Resource
	CoreService coreService;
	@Resource
	RelayService relayService;
	@Resource
	RedPacketService redPacketService;
	@Resource
	BlackUserService blackUserService;
	@Resource
	private PostManService postmanService;
	@Resource
	private ReservationService reservationService;
	@RequestMapping(value = "/index.html", method = RequestMethod.GET)
	public String index(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<Reservation> resList = null; 
		Map<String,Object> parameter = new HashMap<String, Object>();
		parameter.put("rOpenid", "oGpcjwvKHVfi2GvIpt2jy06AM0x0");
		 resList = reservationService.queryListByMap(parameter);
		 session.setAttribute("openid","oGpcjwvKHVfi2GvIpt2jy06AM0x0");
		 session.setAttribute("spread","3");
		//判定是否存在
			if(resList.size()>0 ){
				String rur ="";
				String tags= resList.get(0).getState();
				model.addAttribute("rid",resList.get(0).getId());
				model.addAttribute("openid",resList.get(0).getrOpenid());
				switch (tags) {
				case "UNREAD":
					rur = "resercus/loading";
					break;
				case "RECEIVE":
					rur = "resercus/loading";
					break;
				case "REFUSE":
					rur = "resercus/refuse";
					break;
				case "UNFINISH":
					model.addAttribute("remark", resList.get(0).getRemark());
					rur = "resercus/unfinish";
					break;
				case "FINISH":
					rur = "resercus/fenx";
					break;
				default:
					rur = "resercus/fenm";
					break;
				}
				return rur;
			}else{
				return "resercus/fenm";
			}
			
		
	}
	/**
	 * 跳转授权
	 * @param model
	 * @param session
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/ording.html", method = RequestMethod.GET)
	public void toRight(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String tag =  request.getParameter("spread");
		session.setAttribute("spread", tag);
		Cookie cookie = new Cookie("JSESSIONID", request.getSession().getId());  
	    response.addCookie(cookie);  
		// TODO
		String redUrl =coreService.getReserRight(tag);
		/*String redUrl =coreService.getmyReserRight(tag);*/
		System.out.println(redUrl);
			response.sendRedirect(redUrl);
		
	}
	/**
	 * 约车活动点击送车
	 */
	@RequestMapping(value = "/clchick.html", method = RequestMethod.GET)
	public String chisk(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<Reservation> resList = null; 
		// 获取授权后code
			String code = request.getParameter("code");
			session.setAttribute("code", code);
			String state = request.getParameter("state");
			String openid = "";
			String ua = request.getHeader("user-agent").toLowerCase();
			if(ua.indexOf("micromessenger")>0){
				//code换取抓取用户信息的token
				AccessToken token = coreService.getAccessToken(code, state);
				System.out.println(token);
						// 获取用户微信信息
				if(token.getToken()!=null){
					//抓取用户信息
					WxUserMsg umsg = coreService.catchUserMsg(token);
					//过滤昵称表情符号
					String nk= EmojiFilter.filterEmoji(umsg.getNickname());
					umsg.setNickname(nk); 
					session.setAttribute("openid", umsg.getOpenid());
					openid = umsg.getOpenid();
					if(relayService.selectWxUserByOpenid(umsg.getOpenid())==null){ 
						//存入用户信息
						relayService.saveWxUser(umsg);
					}
					Map<String,Object> parameter = new HashMap<String, Object>();
					parameter.put("rOpenid", umsg.getOpenid());
					 resList = reservationService.queryListByMap(parameter);
				}else{
					return "resercus/fenm";
				}
			}
		// 获得js票
			// TODO
		AccessToken tokenCe = coreService.getAccessTokenC();
		/*AccessToken tokenCe = coreService.getAccessToken(code,state);*/
		Jsticket ticket = coreService.getJsticket(tokenCe);
		/*Jsticket ticket = coreService.getmyJsticket(tokenCe);*/
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		//判定是否存在
		if(resList.size()>0){
			Reservation rese = new Reservation();
			rese = resList.get(0);
			String rur ="";
			String tags= rese.getState();
			int RedsCount = rese.getRedsCount();
			model.addAttribute("rid",rese.getId());
			model.addAttribute("openid",rese.getrOpenid());
			switch (tags) {
			case "UNREAD":
				rur = "resercus/loading";
				break;
			case "RECEIVE":
				rur = "resercus/loading";
				break;
			case "REFUSE":
				rur = "resercus/refuse";
				break;
			case "UNFINISH":
				model.addAttribute("remark", rese.getRemark());
				rur = "resercus/unfinish";
				break;
			case "CANCEL":
				rur = "resercus/fenm";
				break;
			case "BEICANCEL":
				rur = "resercus/syqx";
				break;
			case "FINISH":
				// TODO 查询是否领取9元红包
				
				Map<String,Object> Condition = new HashMap<String,Object>();
				Condition.put("rOpenid", openid);
				List<Reservation> resLsit1 = reservationService.queryListByMap(Condition);
				Reservation reser = resLsit1.get(0);
				if(reser != null && reser.getRedsCount()>0){
					return "resercus/fenm";
				}else{
					reser.setRedsCount(1);
					reservationService.updateReservation(reser);
			/*	Condition.clear();
				Condition.put("count", 9);
				Condition.put("rid", resLsit1.get(0).getId());
				List<RedPacket> redList = redPacketService.selectListByMap(Condition);
				if(redList != null && redList.size()>0){
					return "resercus/fenm";
				}else{
					Condition.clear();
					Condition.put("id", resLsit1.get(0).getId());
					List<Reservation> res = reservationService.queryListByMap(Condition);*/
					//确认完成发放红包
					//createTime
					/*Date now = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
					String nowTime = dateFormat.format(now);
					ParsePosition pos = new ParsePosition(0);
					Date currentTime_2 = dateFormat.parse(nowTime, pos);
					String unique = res.get(0).getPhone();
					RedPacket reds = new RedPacket();
					reds.setRid(resLsit1.get(0).getId());
					reds.setName("约车红包"+System.currentTimeMillis()/1000);
					reds.setUnique(unique);
					reds.setCount(9);
					String begin = JWTCreatorTest.getSecondTimes();
					reds.setBegin(begin);
					reds.setExpiry(7);
					int iat = (int)(System.currentTimeMillis()/1000-30);
					reds.setIat(iat);
					int exp = (int)(System.currentTimeMillis()/1000+300);
					reds.setExp(exp);
					reds.setCreateTime(currentTime_2);
					reds.setDeleteState(1);
					Map<String, Object> header = new HashMap<String, Object>();
			        header.put("typ", "JWT");
			        String signed = JWTCreator.init()
			                .withHeader(header)
			                .withClaim("unique", reds.getUnique())
			                .withClaim("name", reds.getName())
			                .withClaim("count", reds.getCount())
			                .withClaim("begin", reds.getBegin())
			                .withClaim("expiry", reds.getExpiry())
			                .withClaim("iat", reds.getIat())
			                .withClaim("exp", reds.getExp())
			                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
			        
			        System.out.println("https://wechat.car2go.cn/coupon/get/?jwt="+signed);
			        String js= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/get/?jwt="+signed,"GET",null);
					System.out.println(js);
					redPacketService.insertRedPacket(reds);*/
					//返回新预约页面
					rur = "resercus/fenx";
				
				}
				break ;
			default:
				rur = "resercus/fenm";
				break;
			}
			return rur;
		}else{
			return "resercus/fenm";
		}
			
		
	}
	/**
	 * 约车活动开始
	 */
	@RequestMapping(value = "/show.html", method = RequestMethod.GET)
	public String show(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
		//服务器时间
		Date nowtime = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String datenow = format.format(nowtime);
		model.addAttribute("datenow", datenow);
			return "resercus/index";
		
	}
	/**
	 * 检查是否有单未完成
	 */
	@RequestMapping(value = "/checkOrder.html", method = RequestMethod.POST)
	@ResponseBody
	public String checkReservation(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("openid") String openid,@Param("stime") String stime)
			throws Exception {
		SimpleDateFormat dateFormatn = new SimpleDateFormat("yyyy/MM/dd HH:mm");// 可以方便地修改日期格式
		Date sTime = dateFormatn.parse(stime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date minDate = null;
		try {
			minDate = format.parse("2017-01-16 00:00:00");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//检查未完成
		Map<String,Object> Condition = new HashMap<String,Object>();
		Condition.put("rOpenid", openid);
		List<Reservation> resList = reservationService.queryListByMap(Condition);
		for (int i = 0; i < resList.size(); i++) {
			if("FINISH".equals(resList.get(i).getState())||"CANCEL".equals(resList.get(i).getState())
					||"BEICANCEL".equals(resList.get(i).getState())||"REFUSE".equals(resList.get(i).getState())){
			}else{
				return "false";
			}
		}
		if(sTime.getTime()-minDate.getTime()<=0){
			return "outTime";
		}
		
		return "true";
	}
	/**
	 * 约车预约
	 */
	@RequestMapping(value = "/yuyue.html", method = RequestMethod.POST)
	public String yuyue(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,Reservation reser,@Param("stime") String stime)
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
		// 生成随机字符串
		String noncestrs = RandomStringUtils.randomAlphanumeric(4);
		reser.setOrderNo(noncestrs+timestamp);
		//createTime
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		SimpleDateFormat dateFormatn = new SimpleDateFormat("yyyy/MM/dd HH:mm");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		ParsePosition pos = new ParsePosition(0);
		Date currentTime_2 = dateFormat.parse(nowTime, pos);
		reser.setCreateTime(currentTime_2);
		Date sTime = dateFormatn.parse(stime);
		reser.setTime(sTime);
		reser.setSpread((String)session.getAttribute("spread"));
		reser.setState("RECEIVE");
		reser.setRedsCount(0);
		reser.setDeleteState(1);
		if(reser.getPhone().indexOf("+86")==-1){
			reser.setPhone("+86"+reser.getPhone());
		}
		reservationService.insertReservation(reser);
		Reservation resCondition = new Reservation();
		resCondition.setPhone(reser.getPhone());
		resCondition.setTime(sTime);
		List<Reservation> re = reservationService.queryListByEntity(resCondition);
		session.setAttribute("rid", re.get(0).getId());
		session.setAttribute("openid",reser.getrOpenid());
		return "redirect:loading.html";
		
	}
	/**
	 * 判定会员与否
	 */
	@RequestMapping(value = "/members.html", method = RequestMethod.POST)
	@ResponseBody
	public Object members(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("phone")String phone )
			throws Exception {
		Map<String, Object> header = new HashMap<String, Object>();
        header.put("typ", "JWT");
        String signed = JWTCreator.init()
                .withHeader(header)
                .withClaim("unique", phone)
                .withClaim("iat", (int)(System.currentTimeMillis()/1000-30))
                .withClaim("exp", (int)(System.currentTimeMillis()/1000+300))
                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
        System.out.println("https://wechat.car2go.cn/coupon/checkuser?jwt="+signed);
        String js= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/checkuser?jwt="+signed,"GET",null);
        //TODO
       /* js="success";*/
		System.out.println(js);
		if("true".equals(js)){
			//TODO 查询是否在黑名单而且在期限之内
			List<BlackUser> blackList = blackUserService.selectBlack(phone);
			
			if(blackList!=null&&blackList.size()>0){
				BlackUser blackUser=blackList.get(0);
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.YEAR, 50);
				if((blackUser.getBlackEndTime().getTime()-calendar.getTime().getTime())>0){
					return "forever";
				}else{
					return "week";
				}
			}else{
				return js;
			}
		}
		return js;
	}
	public static void main(String[] args) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		Map<String, Object> header = new HashMap<String, Object>();
        header.put("typ", "JWT");
        String signed = JWTCreator.init()
                .withHeader(header)
                .withClaim("unique", "+8618638480014")
                .withClaim("iat", (int)(System.currentTimeMillis()/1000-30))
                .withClaim("exp", (int)(System.currentTimeMillis()/1000+300))
                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
        System.out.println("https://wechat.car2go.cn/coupon/checkuser?jwt="+signed);
        String js= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/checkuser?jwt="+signed,"GET",null);
		System.out.println(js);
	}
	/**
	 * fenm跳转
	 */
	@RequestMapping(value = "/showas.html", method = RequestMethod.GET)
	public String shows(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response )
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
			return "resercus/fenm";
		
	}
	/**
	 * fenm跳转
	 */
	@RequestMapping(value = "/showrule.html", method = RequestMethod.GET)
	public String showrule(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response )
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
			return "resercus/wenben";
		
	}

	/**
	 * 完成等待预约
	 */
	@RequestMapping(value = "/loading.html", method = RequestMethod.GET)
	public String load(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response )
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
			return "resercus/loading";
		
	}
	/**
	 * 完成预约
	 */
	@RequestMapping(value = "/share.html", method = RequestMethod.GET)
	public String fi(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("rid")int rid,@Param("openid")String openid )
			throws Exception {
		model.addAttribute("rid", rid);
		model.addAttribute("openid", openid);
			return "resercus/fenx";
		
	}
	/**
	 * 完成预约 发送反馈
	 */
	@RequestMapping(value = "/cusback.html", method = RequestMethod.POST)
	@ResponseBody
	public void cusback(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("rid")int rid,@Param("openid")String openid,@Param("satisfaction")String satisfaction,@Param("cusBack")String cusBack )
			throws Exception {
		Reservation reser = new Reservation();
		reser.setId(rid);
		reser.setrOpenid(openid);
		reser.setSatisfaction(satisfaction);
		reser.setCusBack(cusBack);
		reservationService.updateReservation(reser);
			
	}
	/**
	 * 取消未完成预约
	 */
	@RequestMapping(value = "/dis", method = RequestMethod.POST)
	public String back(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response ,@Param("rid")int rid,@Param("openid")String openid)
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
		
		Reservation seser = new Reservation();
		seser.setrOpenid(openid);
		seser.setId(rid);
		seser.setState("CANCEL");
		//取消时间
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		ParsePosition pos = new ParsePosition(0);
		Date currentTime_2 = dateFormat.parse(nowTime, pos);
		seser.setCancelTime(currentTime_2);
		reservationService.updateReservation(seser);
		List<Reservation> resList = reservationService.queryListByEntity(seser);
		insertBlackUserByIllegal(resList.get(0));
		return "resercus/fenm";
		
	}
	public void insertBlackUserByIllegal(Reservation reser) throws Exception{
		/*Reservation re = new Reservation();
		re.setPhone(reser.getPhone());
		re.setState("CANCEL");*/
		int tags = reservationService.selectCountIllegal(reser);
		BlackUser blackUser = new BlackUser();
		blackUser.setBlackPhone(reser.getPhone());
		blackUser.setBlackDeleteState(2);
		blackUser.setBlackBeginTime(new Date());
		/*if(tags ==2){
			Date da = blackUser.getBlackBeginTime();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(da);
			calendar.add(Calendar.DATE, 7);
			blackUser.setBlackEndTime(calendar.getTime());
			int w = blackUserService.insertBlackUser(blackUser);
		}else */
			if(tags>=1){
			Date da = blackUser.getBlackBeginTime();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(da);
			calendar.add(Calendar.YEAR,100 );
			blackUser.setBlackEndTime(calendar.getTime());
			int w = blackUserService.insertBlackUser(blackUser);
		}
		
		
	}
	/**
	 * 进入分享链接
	 */
	@RequestMapping(value = "/corn.html", method = RequestMethod.GET)
	public String corn(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response ,@Param("rid")int rid,@Param("openid")String openid,@Param("spread")String spread)
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
		
		model.addAttribute("rid", rid);
		model.addAttribute("openid", openid);
		model.addAttribute("spread", spread);
		int randNum = RandomP.getRandomP();
		Map<String,Object> maps = new HashMap<String,Object>();
		maps.put("id", rid);
		maps.put("rOpenid", openid);
		maps.put("state", "FINISH");
		List<Reservation> resList = reservationService.queryListByMap(maps);
		if(resList.size()>0){
			if(resList.get(0).getRedsCount()<=3){
				if(session.getAttribute("money")!=null && !session.getAttribute("money").equals("")){
					
				}else{
					session.setAttribute("money", randNum);
				}	
			}else{
				model.addAttribute("money", "红包已被领完了~");
				}
			}else{
				model.addAttribute("money", "红包已被领完了~");
			}
			return "resercus/corn";
		
	}
	/**
	 * 接受分享获取红包
	 */
	@RequestMapping(value = "/fenx.html", method = RequestMethod.POST)
	@ResponseBody
	public String fenx(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response ,@Param("rid")int rid,@Param("openid")String openid,@Param("xphone")String xphone,@Param("money")int money)
			throws Exception {
		//判断是否会员
		Map<String, Object> header = new HashMap<String, Object>();
        header.put("typ", "JWT");
        String signed = JWTCreator.init()
                .withHeader(header)
                .withClaim("unique", xphone)
                .withClaim("iat", (int)(System.currentTimeMillis()/1000-30))
                .withClaim("exp", (int)(System.currentTimeMillis()/1000+300))
                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
        System.out.println("https://wechat.car2go.cn/coupon/checkuser?jwt="+signed);
        String js= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/checkuser?jwt="+signed,"GET",null);
        if("true".equals(js)){
        	Map<String,Object> maps = new HashMap<String,Object>();
        	//查询预约

    		maps.put("id", rid);
    		maps.put("rOpenid", openid);
    		maps.put("state", "FINISH");
    		List<Reservation> resList = reservationService.queryListByMap(maps);
    		if(resList.size()>0){
	    			/*if(resList.get(0).getRedsCount()<=3){*/
	    			int randNum = money;
	    			model.addAttribute("money", randNum);
	    			//查询是否领取
	    			maps.clear();
	            	maps.put("rid", rid);
	            	maps.put("unique", xphone);
	            	if(redPacketService.selectUnderNineListByMap(maps).size()>=1){
	            		return "exitNows";
	            	}else{
	            		//发放红包
	        			Date now = new Date();
	        			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
	        			String nowTime = dateFormat.format(now);
	        			ParsePosition pos = new ParsePosition(0);
	        			Date currentTime_2 = dateFormat.parse(nowTime, pos);
	        			RedPacket reds = new RedPacket();
	        			reds.setRid(rid);
	        			reds.setName("约车分享红包"+System.currentTimeMillis() / 1000);
	        			reds.setUnique(xphone);
	        			reds.setCount(randNum);
	        			String begin = JWTCreatorTest.getSecondTimes();
	        			reds.setBegin(begin);
	        			reds.setExpiry(7);
	        			int iat = (int)(System.currentTimeMillis()/1000-30);
	        			reds.setIat(iat);
	        			int exp = (int)(System.currentTimeMillis()/1000+300);
	        			reds.setExp(exp);
	        			reds.setCreateTime(currentTime_2);
	        			reds.setDeleteState(1);
	        			header.clear();
	        	        header.put("typ", "JWT");
	        	         signed = JWTCreator.init()
	        	                .withHeader(header)
	        	                .withClaim("unique", reds.getUnique())
	        	                .withClaim("name", reds.getName())
	        	                .withClaim("count", reds.getCount())
	        	                .withClaim("begin", reds.getBegin())
	        	                .withClaim("expiry", reds.getExpiry())
	        	                .withClaim("iat", reds.getIat())
	        	                .withClaim("exp", reds.getExp())
	        	                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
	        	        
	        	        System.out.println("https://wechat.car2go.cn/coupon/get/?jwt="+signed);
	        	       String jss= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/get/?jwt="+signed,"GET",null);
	        			System.out.println(jss);
	        			if("\"success\"".equals(jss)){
	        				redPacketService.insertRedPacket(reds);
	        				int redc = resList.get(0).getRedsCount()+1;
	    	    			Reservation reservation = new Reservation();
	    	    			reservation.setId(rid);
	    	    			reservation.setrOpenid(openid);
	    	    			reservation.setRedsCount(redc);
	    	    			reservationService.updateReservation(reservation);
	        			}
	        			return js;
	            	}
        	}else{	
        		return "false";
        	}
	        		
        }else{
        	return "false";
        }
		
	}
	/**
	 * 检测会员分享获取红包
	 */
	@RequestMapping(value = "/check.html", method = RequestMethod.POST)
	@ResponseBody
	public String checkMember(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response ,@Param("phone")String phone)
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
		
		
		//判断是否会员
		Map<String, Object> header = new HashMap<String, Object>();
        header.put("typ", "JWT");
        String signed = JWTCreator.init()
                .withHeader(header)
                .withClaim("unique", phone)
                .withClaim("iat", (int)(System.currentTimeMillis()/1000-30))
                .withClaim("exp", (int)(System.currentTimeMillis()/1000+300))
                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
        System.out.println("https://wechat.car2go.cn/coupon/checkuser?jwt="+signed);
        String js= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/checkuser?jwt="+signed,"GET",null);
        return js;
	}
	@RequestMapping(value = "/tofenm.html", method = RequestMethod.GET)
	public String refusetofenm(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
		return "resercus/fenm";
	}
	/**
	 * 
	 */
	@RequestMapping(value = "/flush.html", method = RequestMethod.GET)
	public String out(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("rid")int rid)
			throws Exception {
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		model.addAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		model.addAttribute("noncestr", noncestr);
		// appid
		model.addAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		model.addAttribute("signature", signature);
		
		
		Map<String,Object> parameter = new HashMap<String, Object>();
		parameter.put("id", rid);
		model.addAttribute("rid", rid);
		List<Reservation> resList = reservationService.queryListByMap(parameter);
		//判定是否存在
				if(resList.size()>0){
					Reservation rese = new Reservation();
					rese = resList.get(0);
					String rur ="";
					String tags= rese.getState();
					int RedsCount = rese.getRedsCount();
					model.addAttribute("openid", rese.getrOpenid());
					switch (tags) {
					case "UNREAD":
						rur = "resercus/loading";
						break;
					case "RECEIVE":
						rur = "resercus/loading";
						break;
					case "REFUSE":
						rur = "resercus/refuse";
						break;
					case "UNFINISH":
						model.addAttribute("remark", rese.getRemark());
						rur = "resercus/unfinish";
						break;
					case "CANCEL":
						rur = "resercus/fenm";
						break;
					case "BEICANCEL":
						rur = "resercus/syqx";
						break;
					case "FINISH":
						// TODO 查询是否领取9元红包
						Map<String,Object> Condition = new HashMap<String,Object>();
						Condition.put("rid", rid);
						List<Reservation> resLsit1 = reservationService.queryListByMap(Condition);
						Reservation reser = resLsit1.get(0);
						if(reser != null && reser.getRedsCount()>0){
							return "resercus/fenm";
						}else{
							reser.setRedsCount(1);
							reservationService.updateReservation(reser);
						/*if(redList != null && redList.size()>0){
							return "resercus/fenm";
						}else{
							Condition.clear();
							Condition.put("id", rid);
							List<Reservation> res = reservationService.queryListByMap(Condition);
							//确认完成发放红包
							//createTime
							Date now = new Date();
							SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
							String nowTime = dateFormat.format(now);
							ParsePosition pos = new ParsePosition(0);
							Date currentTime_2 = dateFormat.parse(nowTime, pos);
							String unique = res.get(0).getPhone();
							RedPacket reds = new RedPacket();
							reds.setRid(rid);
							reds.setName("约车红包"+System.currentTimeMillis()/1000);
							reds.setUnique(unique);
							reds.setCount(9);
							String begin = JWTCreatorTest.getSecondTimes();
							reds.setBegin(begin);
							reds.setExpiry(7);
							int iat = (int)(System.currentTimeMillis()/1000-30);
							reds.setIat(iat);
							int exp = (int)(System.currentTimeMillis()/1000+300);
							reds.setExp(exp);
							reds.setCreateTime(currentTime_2);
							reds.setDeleteState(1);
							Map<String, Object> header = new HashMap<String, Object>();
					        header.put("typ", "JWT");
					        String signed = JWTCreator.init()
					                .withHeader(header)
					                .withClaim("unique", reds.getUnique())
					                .withClaim("name", reds.getName())
					                .withClaim("count", reds.getCount())
					                .withClaim("begin", reds.getBegin())
					                .withClaim("expiry", reds.getExpiry())
					                .withClaim("iat", reds.getIat())
					                .withClaim("exp", reds.getExp())
					                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
					        
					        System.out.println("https://wechat.car2go.cn/coupon/get/?jwt="+signed);
					        String js= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/get/?jwt="+signed,"GET",null);
							System.out.println(js);
							redPacketService.insertRedPacket(reds);*/
							//返回新预约页面
							rur = "resercus/fenx";
						}
						break;
					default:
						rur = "resercus/fenm";
						break;
					}
					return rur;
				}else{
					return "resercus/fenm";
				}
	}


	
}
